import { defineStore } from 'pinia'
import request from "@/api/request.js"
import router from '@/router/index.js'

let modules = import.meta.glob("@/views/**/*.vue")
export let useSysStore = defineStore('sys', {
    state: () => {
        return {
            modules: [],
            activeModule: undefined,
            activeModuleName: undefined,
            activeMenuName: undefined,
            permissionsList: [],
        }
    },
    getters: {
        getActiveMenuName() {
            if (!this.activeMenuName) {
                this.activeMenuName = sessionStorage.getItem("activeMenuName")
            }

            return this.activeMenuName
        },
        getActiveModuleName() {
            if (!this.activeModuleName) {
                this.activeModuleName = sessionStorage.getItem("activeModule")
            }
            if (!this.activeModuleName) {
                this.activeModuleName = "home"
            }
            return this.activeModuleName
        }
    },
    actions: {
        async hasPermission(perm) {
            let p = this.permissionsList.find(item => item.perm == perm)
            return p
        },
        async loadPermissions() {
            await request({
                url: "/permissions/tree"
            }).then(res => {
                this.modules = res.data
                dynamicRoutes(this.modules, this.permissionsList)
                console.log(router.getRoutes())
            });
            return true
        },
        switchActiveModule(name) {
            sessionStorage.setItem("activeModule", name)
            if (name == "home") {
                router.push("/home")
                return;
            }
            let active = this.permissionsList.find(item => item.menuEname == name);
            this.activeModule = active.children
            this.activeModuleName = active.menuEname
            router.push(active.path)
        }
    }
})
function dynamicRoutes(routes, permissionsList) {
    for (let item of routes) {
        let route = {
            path: item.path,
            name: item.menuEname,
            component: modules["/src/views" + item.component + ".vue"]
        }
        // let permission = {...item}

        permissionsList.push({ ...item })
        router.addRoute(item.parentName, route)
        if (item.children && item.children.length > 0) {
            dynamicRoutes(item.children, permissionsList)
        }
    }
}